package com.compass.doctor.ui.mine

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Bundle
import androidx.activity.viewModels
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.databinding.ActivityCaSignatureBinding
import com.compass.doctor.ui.mine.viewmodel.MineViewModel
import com.compass.framework.ext.onClick
import com.compass.framework.manager.UserInfoManager
import java.io.File
import java.io.FileOutputStream

/**
 * Description： CA签名
 * Date:2024/3/8 15:13
 */
class CaSignatureActivity : BaseVBActivity<ActivityCaSignatureBinding>() {

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, CaSignatureActivity::class.java)
            context.startActivity(intent)
        }
    }

    private val mineViewModel: MineViewModel by viewModels()
    private  var bitmap:Bitmap?=null
    override fun initView(savedInstanceState: Bundle?) {


    }

    override fun initData() {
        mineViewModel.updateLiveData.observe(this) {
            it?.let {
                UserInfoManager.saveCA(it)
                showToast("CA签名上传成功")
                finish()
            }
            dismissLoading()
        }
    }

    override fun intListener() {
        mBinding.btnUndo.onClick {
            //回撤
            mBinding.llSignPanel.undo()

        }

        mBinding.btnSave.onClick {
            bitmap = mBinding.llSignPanel.bitmap
            bitmap?.let {
                saveBitmapToAlbum(it)
            }?:kotlin.run {
                showToast("请手写签名后再保存")
            }


        }

        mBinding.tvTitleBar.getRightTextView().onClick {

            //清除
            mBinding.llSignPanel.redo()


        }


    }

    /**
     * 保存bitmap到相册
     */
    private fun saveBitmapToAlbum(sourceBitmap: Bitmap) {
        val bitmap =
            Bitmap.createBitmap(sourceBitmap.width, sourceBitmap.height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
        val paint = Paint()
        paint.color = Color.TRANSPARENT
        //使用Paint绘制新Bitmap，并设置背景色
        canvas.drawRect(0f, 0f, canvas.width.toFloat(), canvas.height.toFloat(), paint)
        //绘制原始Bitmap到新Bitmap
        canvas.drawBitmap(sourceBitmap, 0f, 0f, null)

        val appDir = File(externalCacheDir, "image")
        if (!appDir.exists()) {
            appDir.mkdir()
        }
        val fileName = "IMG_CA.png"
        val file = File(appDir, fileName)
        try {
            val fos = FileOutputStream(file)
            fos.use { fos ->
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)
                fos.flush()
                fos.close()
            }
            showLoading()
            mineViewModel.uploadCA(file)

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

}